extends Node2D

const ARC_POINTS := 8

@onready var area_2d: Area2D = $Area2D
@onready var card_arc: Line2D = $CanvasLayer/CardArc

var cur_player_unit: Player
var targeting := false


func _ready() -> void:
	Events.player_attack_target_start.connect(_on_player_attack_target_start)
	Events.player_attack_target_end.connect(_on_player_attack_target_end)

func _process(delta: float) -> void:
	if not targeting:
		return
		
	area_2d.position = get_local_mouse_position()
	card_arc.points = _get_points()	
	
func _get_points() -> Array:
	var points := []
	var start := cur_player_unit.global_position
	#start.x += (cur_player_unit.size.x / 2)
	start.x += 8
	var target := get_local_mouse_position()
	var distance := (target - start)
	
	for i in range(ARC_POINTS):
		var t := (1.0 / ARC_POINTS) * i
		var x := start.x + (distance.x / ARC_POINTS) * i
		var y := start.y + ease_out_cubic(t) * distance.y
		points.append(Vector2(x, y))
	points.append(target)
	
	return points
	
func ease_out_cubic(number : float) -> float:
	return 1.0 - pow(1.0 - number, 3.0)
	

func _on_player_attack_target_start(_player_unit: Player) -> void:
	#if not _card.card.is_single_targeted():
		#return
	area_2d.collision_mask = 4
	var enemies = get_tree().get_nodes_in_group("enemies")
	for unit in enemies:
		unit.monitoring = true
		unit.monitorable = true

	#var player_units = get_tree().get_nodes_in_group("player")
	#for unit in player_units:
		#unit.monitoring = false
		#unit.monitorable = false
		
	targeting = true
	area_2d.monitoring = true
	area_2d.monitorable = true
	cur_player_unit = _player_unit
	
func _on_player_attack_target_end(_player_unit: Player) -> void:
	targeting = false
	card_arc.clear_points()
	area_2d.position = Vector2.ZERO
	area_2d.monitorable = false
	area_2d.monitoring = false

	var enemies = get_tree().get_nodes_in_group("enemies")
	for unit in enemies:
		unit.monitoring = false
		unit.monitorable = false
	
	var player_units = get_tree().get_nodes_in_group("player")
	for unit in player_units:
		unit.monitoring = true
		unit.monitorable = true
	cur_player_unit = null
	
	
func _on_area_2d_area_entered(area: Area2D) -> void:
	if not cur_player_unit or not targeting:
		return
	
	if not cur_player_unit.targets.has(area):
		cur_player_unit.targets.append(area)

func _on_area_2d_area_exited(area: Area2D) -> void:
	if not cur_player_unit or not targeting:
		return
		
	cur_player_unit.targets.erase(area)
